package com.example.administrator.dc.Activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.dc.Bean.AddImage;
import com.example.administrator.dc.Class.BlueFilter;
import com.example.administrator.dc.Class.GrayFilter;
import com.example.administrator.dc.Class.GreenFilter;
import com.example.administrator.dc.Class.Polaroid;
import com.example.administrator.dc.Class.RedFilter;
import com.example.administrator.dc.Class.order_time;
import com.example.administrator.dc.Class.typecolor;
import com.example.administrator.dc.R;
import com.example.administrator.dc.Service.CollectListener;
import com.example.administrator.dc.Service.imageUp;
import com.example.administrator.dc.model.Contants;
import com.example.administrator.dc.model.ImageListenr;
import com.example.administrator.dc.model.UploadUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UploadActivity extends BaseActivity  implements ImageListenr {
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1;
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    private  Context context;
    private EditText Content;
    private String fileName;
    private ImageView Send;
    private Button blackwhite, tijiao;
    private Button colors, ord, colortype, blue, green, red;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        Content = (EditText) findViewById(R.id.content);
        Send = (ImageView) findViewById(R.id.send);
        blackwhite = (Button) findViewById(R.id.blackwhite1);
        colors = (Button) findViewById(R.id.color1);
        ord = (Button) findViewById(R.id.colorord);
        colortype = (Button) findViewById(R.id.colortype);
        blue = (Button) findViewById(R.id.blue);
        green = (Button) findViewById(R.id.green);
        red = (Button) findViewById(R.id.red);
        tijiao = (Button) findViewById(R.id.comment1);

        Send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                select();

            }
        });
        tijiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String title=Content.getText().toString();
               SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
                String userid = sp.getString("user_id", null);
               UploadUtil u = new UploadUtil();
                u.pic(fileName, title, userid,UploadActivity.this);

            }
        });
    }

    private void select() {
        final int[] yourChoice = new int[1];

        final String[] items = {"拍照", "本地图片"};
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(UploadActivity.this);
        singleChoiceDialog.setTitle("选取照片方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice[0] = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice[0] != -1) {
                            if (items[yourChoice[0]].equals("拍照")) {
                                getImageFromCamera();


                            }
                            if (items[yourChoice[0]].equals("本地图片")) {

                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setType("image/*");//相片类型
                                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                                Toast.makeText(UploadActivity.this,
                                        "你选择了" + items[yourChoice[0]],
                                        Toast.LENGTH_SHORT).show();

                            }

                    }
                    }
                });
        singleChoiceDialog.show();
    }
    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri uri = data.getData();
            if (uri == null) {
                //use bundle to get data
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
                    String userid = sp.getString("user_id", null);
                    final Bitmap photo = (Bitmap) bundle.get("data");
                    final Bitmap[] image = new Bitmap[1];

                 /*   GrayFilter grayFilter=new GrayFilter();
                    grayFilter.changeToGray(photo);*/
                    // Send.setImageBitmap( grayFilter.changeToGray(photo));
                    blackwhite.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GrayFilter grayFilter = new GrayFilter();
                            Send.setImageBitmap(grayFilter.changeToGray(photo));
                            image[0] = grayFilter.changeToGray(photo);
                            saveImage(image[0], "111");
                        }
                    });
                    colors.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Polaroid grayFilter = new Polaroid();
                            Send.setImageBitmap(grayFilter.changePolaroid(photo));
                            image[0] = grayFilter.changePolaroid(photo);
                            saveImage(image[0], "111");
                        }
                    });
                    ord.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            order_time ordFilter = new order_time();
                            Send.setImageBitmap(ordFilter.changeorder(photo));
                            image[0] = ordFilter.changeorder(photo);
                            saveImage(image[0], "111");
                        }
                    });
                    colortype.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            typecolor typeFilter = new typecolor();
                            Send.setImageBitmap(typeFilter.type(photo));
                            image[0] = typeFilter.type(photo);
                            saveImage(image[0], "111");
                        }
                    });
                    green.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GreenFilter typeFilter = new GreenFilter();
                            Send.setImageBitmap(typeFilter.changeGreen(photo));
                            image[0] = typeFilter.changeGreen(photo);
                            saveImage(image[0], "111");

                        }
                    });
                    blue.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            BlueFilter typeFilter = new BlueFilter();
                            Send.setImageBitmap(typeFilter.changeblue(photo));
                            image[0] = typeFilter.changeblue(photo);
                            saveImage(image[0], "111");
                        }
                    });
                    red.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            RedFilter typeFilter = new RedFilter();
                            Send.setImageBitmap(typeFilter.changered(photo));
                            image[0] = typeFilter.changered(photo);
                            saveImage(image[0], "111");
                        }
                    });
                 /*   tijiao.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
                            String userid =sp.getString("user_id", null);
                            UploadUtil u=new UploadUtil();
                            u.Upload(image[0],"111",userid);
                        }
                    });*/


                 /*   UploadUtil u=new UploadUtil();
                    u.Upload(photo,"111",userid);*/
                }
                }
            else {
                uri = data.getData();
                if (uri != null) {
                    //use bundle to get data
                    SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
                    String userid = sp.getString("user_id", null);
                  String mingzi=  getRealPathFromUri(this,uri);
                    int y= mingzi.lastIndexOf("/");
                    fileName=mingzi.substring(y+1);
                    final Bitmap photo = getDiskBitmap(getRealPathFromUri(this,uri));
                    saveImage(photo, "111");
                    blackwhite.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GrayFilter grayFilter = new GrayFilter();
                            Send.setImageBitmap(grayFilter.changeToGray(photo));
                        }
                    });
                    colors.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Polaroid grayFilter = new Polaroid();
                            Send.setImageBitmap(grayFilter.changePolaroid(photo));

                        }
                    });
                    ord.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            order_time ordFilter = new order_time();
                            Send.setImageBitmap(ordFilter.changeorder(photo));

                        }
                    });
                    colortype.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            typecolor typeFilter = new typecolor();
                            Send.setImageBitmap(typeFilter.type(photo));

                        }
                    });
                    green.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GreenFilter typeFilter = new GreenFilter();
                            Send.setImageBitmap(typeFilter.changeGreen(photo));


                        }
                    });
                    blue.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            BlueFilter typeFilter = new BlueFilter();
                            Send.setImageBitmap(typeFilter.changeblue(photo));

                        }
                    });
                    red.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            RedFilter typeFilter = new RedFilter();
                            Send.setImageBitmap(typeFilter.changered(photo));


                        }
                    });
                    //      Send.setImageDrawable(this.getDrawable(R.drawable.camera));
                  /*  UploadUtil u=new UploadUtil();
                    u.Upload(photo,"111",userid);*/
                  //  saveImage(photo, "123431");

                } else {
                    Toast.makeText(getApplicationContext(), "err****", Toast.LENGTH_LONG).show();
                    return;
                }
            }
            }
            //to do find the path of pic by uri

        }


    public void saveImage(Bitmap photo, String spath) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Bitmap endBit = Bitmap.createScaledBitmap(photo, 400, 400, true); //创建新的图像大小
            endBit.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public  void  tijiao(final String fileName, final String Title, final String userid){

          /*      SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
                dff.setTimeZone(TimeZone.getTimeZone("GMT+08"));
                String ee = dff.format(new Date());
                Retrofit retrofit=new Retrofit.Builder().baseUrl(Contants.BASE_URL1).
                        addConverterFactory(GsonConverterFactory.create()).build();
                imageUp service=retrofit.create(imageUp.class);
                Call<AddImage> call= service.addoimage(userid,Title,ee+"/"+fileName);
                call.enqueue(new Callback<AddImage>() {
                    @Override
                    public void onResponse(Call<AddImage> call, Response<AddImage> response) {
                        if(response.body().getStatus()==1){


                        }
                        else {
                            response.body().getMessage();
                        }

                    }

                    @Override
                    public void onFailure(Call<AddImage> call, Throwable t) {

                    }
                });*/





    }
    private Bitmap getDiskBitmap(String url)
    {
        Bitmap bitmap = null;
        try
        {
            File file = new File(String.valueOf(url));
            if(file.exists())
            {
                bitmap = BitmapFactory.decodeFile(String.valueOf(url));
            }
        } catch (Exception e)
        {
            // TODO: handle exception
        }

        return bitmap;
    }
    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    @Override
    public void onResponse(String msg) {

    }

    @Override
    public void onFail(String s) {

    }

    @Override
    public void onExitResponse(String msg) {

    }

    @Override
    public void onExitFail(String s) {

    }

    @Override
    public void onFailResponse(String msg) {

    }

    @Override
    public void onResponse1(String msg, String title, String userid) {

            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
            dff.setTimeZone(TimeZone.getTimeZone("GMT+08"));
            String ee = dff.format(new Date());
            Retrofit retrofit=new Retrofit.Builder().baseUrl(Contants.BASE_URL1).
                    addConverterFactory(GsonConverterFactory.create()).build();
            final imageUp service=retrofit.create(imageUp.class);
            Call<AddImage> call= service.addoimage(userid,title,ee+"/"+msg);
            call.enqueue(new Callback<AddImage>() {
                @Override
                public void onResponse(Call<AddImage> call, Response<AddImage> response) {
                    if(response.body().getStatus()==1){
                        Toast.makeText(UploadActivity.this,"成功",Toast.LENGTH_LONG).show();
                        Intent intent=new Intent();
                        intent.setClass(UploadActivity.this,PhotoImage.class);
                        startActivity(intent);


                    }
                    else {
                        response.body().getMessage();
                    }

                }

                @Override
                public void onFailure(Call<AddImage> call, Throwable t) {

                }
            });


            }
        }



